import amqp from "amqplib";
import { DanmakuMQ, GiftMQ } from "../declare/liver";
const StoreConfig = require("../config/store.json");
const NODE_ENV = process.env.NODE_ENV || "development";
const rabbitconfig = StoreConfig[NODE_ENV]["rabbitmq"];
const QUEUE_GIFT_MSG = 'queue.ac.live.gift';
const QUEUE_DANMAKU_MSG = 'queue.ac.live.danmu';
let connection: amqp.Connection | null = null;
let channel: amqp.Channel | null = null;

export default class RabbitMq {
  public async sendGift(giftMsg: GiftMQ) {
    const chn = await this.getChannel();
    const ast = await chn.assertQueue(QUEUE_GIFT_MSG);
    if(ast){
        chn.sendToQueue(QUEUE_GIFT_MSG,Buffer.from(JSON.stringify(giftMsg)))
    }
  }

  public async sendDanmaku(danmakaMsg: DanmakuMQ) {
    const chn = await this.getChannel();
    const ast = await chn.assertQueue(QUEUE_DANMAKU_MSG);
    if(ast){
        chn.sendToQueue(QUEUE_DANMAKU_MSG,Buffer.from(JSON.stringify(danmakaMsg)))
    }
  }
  private async getChannel(): Promise<amqp.Channel> {
    if (!connection) connection = await amqp.connect(rabbitconfig.url);
    if (!channel) channel = await connection.createChannel();
    return channel;
  }
}
